# -*- coding: utf-8 -*-

import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class SichuanGuangyuanPolicy(BaseTaxPolicySpider):
    name = 'sichuan_guangyuan_policy'

    province = '四川省'
    city = '广元市'
    # county = ''
    park = ''
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 500, 200, 202, 502, 429],
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": None,
                # },
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url, path in [
            ['广元市人民政府', "", "https://www.cngy.gov.cn/artic/list/20200415172718120.html", "首页 >政务公开》 政府信息公开 > 政策 > 行政性规范文件"],
            ['广元市人民政府', "", "https://www.cngy.gov.cn/zcwjk.html", "首页 >政务公开》 政府信息公开 > 政策 > 其他文件"],
        ]:
            path = path.split('>')[-1].strip()
            item = {'source': source, 'county': county}
            if '/list/' not in url:
                callback = self.parse_ajax
            else:
                callback = self.parse_content
            yield scrapy.Request(url, callback=callback, meta={'item': item, 'path': path}, dont_filter=True)

    def parse_content(self, response, **kwargs):
        meta = response.meta
        url = response.xpath(".").re_first(r"window.location.href\s*=\s*\"(.*?)\";")
        yield response.follow(url, callback=self.parse_ajax, meta=meta, dont_filter=True, )

    def parse_ajax(self, response, **kwargs):
        meta = response.meta
        path = meta['path']
        re_data = response.xpath(f"//a[contains(text(), '{path}(')]/@href").re(r"\('(.*?)','(.*?)',\d+\)")
        # if url:
        data = {
            'action': f'get_{re_data[0]}_list',
            'pageindex': '1',
            'pagesize': '100',
            'flid': f'{re_data[1]}',
        }
        meta.update({'data': data})
        yield scrapy.FormRequest(response.urljoin('/tools/submit_ajax.ashx'),
                                 callback=self.parse_list, meta=meta, dont_filter=True,
                                 formdata=data,
                                 method="POST",
                                 )

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = meta.get('item')
        data = meta['data']
        json_datas = response.json()['Data']
        elem_list = json_datas['Items']
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem['LinkUrl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['PubTime']
            item['title'] = elem['title']
            if item['publish_date'] < '2022-01-01':
                # self.get_next = None
                pass
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(json.dumps(data, separators=(',', ':')), item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if (self.get_next or self.get_next == '0') and meta.get('is_next') is not False:
            total_page = json_datas['TotalPages']
            print(json.dumps(data, separators=(',', ':')), total_page)
            for page_num in range(2, total_page + 1):
                data['pageindex'] = str(page_num)
                meta.update({'item': prev_item, 'is_next': False})
                yield scrapy.FormRequest(response.url, callback=self.parse_list, meta=meta, formdata=data)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        # item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get() or response.xpath("/title/text()").get()
        # item['publish_date'] = response.xpath("//span[contains(.//text(), '发布时间')]/following-sibling::span//text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_guangyuan_policy -a get_next=0".split())
